package top.javadev.typora.minio.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Properties;

import top.javadev.typora.minio.App;
import top.javadev.typora.minio.config.UploadConfig;

/**
 * @author javadev.top
 * @date 2021/10/11
 */
public class Utils {
    /**
     * 英文点分割，得到后缀
     *
     * @param path
     *            路径
     * @return {@link String}
     */
    public static String getSuffix(String path) {
        if (path != null && path.indexOf(".") > -1) {
            return path.substring(path.lastIndexOf("."));
        } else {
            return "";
        }
    }

    /**
     * 获取运行jar包所在路径，以/结尾
     *
     * @return {@link String}
     */
    public static String getWorkDir() {
        String libPath = new App().getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        String basePath = libPath.substring(0, libPath.lastIndexOf("/") + 1);
        try {
            // 解决中午路径编码问题
            basePath = URLDecoder.decode(basePath, "utf-8");
        } catch (UnsupportedEncodingException e) {
            System.err.println("解码失败：" + e.getMessage());
        }
        return basePath;
    }

    public static UploadConfig loadConfig() {
        File configFile = new File(getWorkDir() + "conf.properties");

        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(configFile));
        } catch (IOException e) {
            System.err.println("配置文件加载失败：" + e.getMessage());
        }
        String ak = properties.getProperty("accessKey");
        String sk = properties.getProperty("secretKey");
        String host = properties.getProperty("host");
        String bucketName = properties.getProperty("bucketName");
        String customKey = properties.getProperty("customKey");

        UploadConfig config = new UploadConfig();
        config.setAccessKey(ak);
        config.setSecretKey(sk);
        config.setHost(host);
        config.setBucketName(bucketName);
        config.setCustomKey(customKey);
        return config;
    }
}
